<template>
  <a-modal
    v-model:visible="visible"
    :title="`${toText}活动`"
    :width="600"
    centered
    wrap-class-name="activity-dialog"
    :label-col="{ style: { width: '125px' } }"
    :mask-closable="false"
    :ok-button-props="{ loading: submitting }"
    :cancel-button-props="{ disabled: submitting }"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-form ref="FormRef" :rules="formRules" :model="formFields">
        <a-form-item name="productType" label="版本">
          <a-radio-group v-model:value="formFields.productType" :options="daysbanben" />
        </a-form-item>

        <a-form-item name="daysType" label="推广时长">
          <a-radio-group v-model:value="formFields.daysType" :options="daysTypeOption" />
        </a-form-item>
        <a-form-item name="type" label="活动类型">
          <a-radio-group v-model:value="formFields.type" disabled :options="activityTypeOptions" />
        </a-form-item>
        <a-form-item name="startTime" label="活动时间">
          <a-range-picker show-time v-model:value="dateRange" value-format="YYYY-MM-DD HH:mm:ss" />
        </a-form-item>
        <a-form-item name="highestHeat" label="赠词热度" v-if="formFields.type === ActivityTypeEnum.Word">
          <a-input v-model:value.trim.number="formFields.highestHeat" placeholder="请输入赠词热度" class="heat-rate" />
        </a-form-item>
        <Divider />

        <div v-for="(rule, index) in formFields.freeWordRules" :key="rule.key">
          <h3 class="ft-16 flex items-center justify-between">
            <span>{{ `活动规则${index + 1}` }}</span>
            <a-button type="text" danger @click="removeRule(index)" :disabled="index === 0">
              <template #icon><delete-outlined /></template>
              删除
            </a-button>
          </h3>
          <a-form-item
            label="最低价(≤)"
            label-align="left"
            :label-col="{ style: { width: '90px' } }"
            :name="['freeWordRules', index, 'lowPrice']"
            :rules="{
              required: true,
              validator: (...args) => checkLowPrice(...args, rule),
              trigger: 'blur'
            }"
          >
            <a-input v-model:value.trim.number="rule.lowPrice" placeholder="请输入最低价" />
          </a-form-item>
          <a-form-item
            label="最高价(&lt;)"
            label-align="left"
            :label-col="{ style: { width: '90px' } }"
            :name="['freeWordRules', index, 'highPrice']"
            :rules="{
              required: true,
              validator: (...args) => checkHighPrice(...args, rule),
              trigger: 'blur'
            }"
          >
            <a-input v-model:value.trim.number="rule.highPrice" placeholder="请输入最高价" />
          </a-form-item>
          <a-form-item
            label="自填词数"
            label-align="left"
            :label-col="{ style: { width: '90px' } }"
            :name="['freeWordRules', index, 'wordNum']"
            :rules="{
              required: true,
              message: '请输入自填词数',
              trigger: 'blur'
            }"
          >
            <a-input v-model:value.trim.number="rule.wordNum" placeholder="请输入自填词数" />
          </a-form-item>
          <a-form-item
            label="组合词数"
            label-align="left"
            :label-col="{ style: { width: '90px' } }"
            :name="['freeWordRules', index, 'combinedWordNum']"
            :rules="{
              required: true,
              message: '请输入组合词数',
              trigger: 'blur'
            }"
          >
            <a-input v-model:value.trim.number="rule.combinedWordNum" placeholder="请输入组合词数" />
          </a-form-item>
          <a-form-item
            label="Pc端赠图"
            label-align="left"
            :label-col="{ style: { width: '90px' } }"
            :name="['freeWordRules', index, 'pcImgNum']"
          >
            <a-radio-group v-model:value="rule.pcImgNum" @change="changeYdImgNum(rule)">
              <a-radio :value="0">无</a-radio>
              <a-radio :value="1">1个</a-radio>
              <a-radio :value="4">4个</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            label="移动端赠图"
            label-align="left"
            :label-col="{ style: { width: '90px' } }"
            :name="['freeWordRules', index, 'ydImgNum']"
          >
            <a-radio-group disabled v-model:value="rule.ydImgNum">
              <a-radio :value="0">无</a-radio>
              <a-radio :value="1">1个</a-radio>
              <a-radio :value="3">3个</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="规则可视化" label-align="left" :label-col="{ style: { width: '90px' } }">
            <span class="text-red-500">{{ rule.lowPrice || 0 }}(元)</span>
            <span>&nbsp;≤&nbsp;提单价&nbsp;&lt;&nbsp;</span>
            <span class="text-red-500">{{ rule.highPrice || 0 }}(元)</span>
            <span>
              赠送
              <span class="text-red-500">{{ rule.wordNum || 0 }}</span>
              个自填关键词
            </span>
            <span
              >或<span class="text-red-500">{{ rule.combinedWordNum || 0 }}</span
              >个组合关键词</span
            >
            <span
              >和<span class="text-red-500">{{ rule.pcImgNum || 0 }}</span
              >个PC端赠图数量</span
            >
            <span
              >和<span class="text-red-500">{{ rule.ydImgNum || 0 }}</span
              >个移动端赠图数量</span
            >
          </a-form-item>
        </div>

        <a-form-item>
          <a-button type="dashed" block @click="updateRule">
            <PlusOutlined />
            新增活动规则
          </a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup name="ActivityUpdater">
import { computed, onMounted, ref } from 'vue'
import { useVModel } from '@vueuse/core'
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue'
import is from '@/utils/is'
import { toLabelValue } from '@/utils'
import type { Rule } from 'ant-design-vue/lib/form'
import type { FormInstance } from 'ant-design-vue'
import { isNil, omit } from 'lodash-es'
import Divider from '@/components/divider/index.vue'
import type { ActivityFields } from '@/services/activity/updateActivity'
import { ActivityTypeKeyMap } from '@/core/mapper/activity'
import { ActivityTypeEnum } from '@/core/enums/type'
import { Mode } from '@/core/interfaces/common'
import { ComboPriceNameEnum } from '@/core/enums/name'

interface Props {
  show: boolean
  submitting: boolean
  loading: boolean
  data: Partial<ActivityFields>
  mode: Mode
  productType: string
}

interface Emits {
  (e: 'on-submit'): void
  (e: 'on-update-rule'): void
  (e: 'update:show'): void
  (e: 'update:data'): void
}

const props = withDefaults(defineProps<Props>(), {
  show: false,
  submitting: false,
  loading: false,
  data: () => ({}),
  mode: Mode.create,
  productType: '百搜版'
})

const FormRef = ref<FormInstance>()
const emit = defineEmits<Emits>()
const visible = useVModel(props, 'show', emit)
const formFields = useVModel(props, 'data', emit)
const activityTypeOptions = toLabelValue(omit(ActivityTypeKeyMap, ActivityTypeEnum.All))
const toText = computed(() => {
  return props.mode === Mode.create ? '新增' : '编辑'
})
console.log(formFields, 'formFieldsformFieldsformFields')
const daysTypeOption = ref([
  {
    label: ComboPriceNameEnum.YEAR,
    value: ComboPriceNameEnum.YEAR
  },
  {
    label: ComboPriceNameEnum.TwoYEAR,
    value: ComboPriceNameEnum.TwoYEAR
  }
])

const daysbanben = ref([
  {
    label: ComboPriceNameEnum.BAXIN,
    value: ComboPriceNameEnum.BAXIN
  },
  {
    label: ComboPriceNameEnum.BSAO,
    value: ComboPriceNameEnum.BSAO
  }
])

console.log(ComboPriceNameEnum.BAXIN, ComboPriceNameEnum.BSAO)

const dateRange = computed({
  set(val: string[]) {
    if (val) {
      const [startTime, endTime] = val
      formFields.value.startTime = startTime
      formFields.value.endTime = endTime
    } else {
      formFields.value.startTime = ''
      formFields.value.endTime = ''
    }
  },
  get() {
    if (formFields.value.startTime && formFields.value.endTime) {
      return [formFields.value.startTime, formFields.value.endTime]
    } else {
      return []
    }
  }
})

const formRules = {
  daysType: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择推广时长'
    }
  ],
  productType: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择版本'
    }
  ],
  type: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择活动类型'
    }
  ],
  status: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择活动状态'
    }
  ],
  startTime: [
    {
      required: true,
      trigger: 'blur',
      message: '请选择开始和结束时间'
    }
  ],
  highestHeat: [
    {
      required: true,
      trigger: 'blur',
      validator: checkHighestHeat
    }
  ]
}

type FreeWordRule = Required<ActivityFields['freeWordRules'][number]>

function checkHighestHeat(_: Rule, value: string) {
  if (value === '' || isNil(value)) {
    return Promise.reject('请输入赠词热度')
  }

  if (is.number(value)) {
    return Promise.resolve()
  } else {
    return Promise.reject('赠词热度必须为数字')
  }
}

// 给移动端配图赋值
function changeYdImgNum(val: any) {
  formFields.value.freeWordRules?.forEach((item) => {
    if (item.key === val.key) {
      if (item.pcImgNum === 0) {
        item.ydImgNum = 0
      } else if (item.pcImgNum === 1) {
        item.ydImgNum = 1
      } else if (item.pcImgNum === 4) {
        item.ydImgNum = 3
      }
    }
  })
}

function checkLowPrice(_: Rule, value: string, callback: () => void, freeWordRules: FreeWordRule) {
  let { lowPrice, highPrice } = freeWordRules

  if (isNil(lowPrice)) {
    return Promise.reject('最低价不能为空')
  }

  if (lowPrice > highPrice) {
    return Promise.reject('最低价不能高于最高价')
  }

  return checkPriceRangeUnion(freeWordRules)
}

function checkHighPrice(_: Rule, value: string, callback: () => void, freeWordRules: FreeWordRule) {
  const { lowPrice, highPrice } = freeWordRules

  if (isNil(highPrice)) {
    return Promise.reject('最高价不能为空')
  }

  if (lowPrice > highPrice) {
    return Promise.reject('最高价不能低于最低价')
  }

  return checkPriceRangeUnion(freeWordRules)
}

function checkPriceRangeUnion(freeWordRules: FreeWordRule) {
  const { lowPrice, highPrice, key } = freeWordRules

  if (is.number(lowPrice) && is.number(highPrice)) {
    const success = (formFields.value.freeWordRules as FreeWordRule[])
      .filter((word) => key !== word.key)
      .filter((word) => is.number(word.lowPrice) && is.number(word.highPrice))
    // .every((word) => {
    //   const lowInRange = inRange(lowPrice, word.lowPrice, word.highPrice)
    //   const highInRange = inRange(highPrice, word.lowPrice, word.highPrice)
    //   if (!lowInRange && !highInRange) {
    //     // 考虑到并集情况
    //     if (lowPrice < word.lowPrice && highPrice > word.highPrice) {
    //       return false
    //     } else {
    //       return true
    //     }
    //   } else {
    //     return false
    //   }
    // })

    if (success) {
      return Promise.resolve()
    } else {
      return Promise.reject('价格区间不能与其他活动价格区间重叠')
    }
  } else {
    return Promise.reject('价格必须为数字')
  }
}

function removeRule(index: number) {
  if (index !== -1) {
    ;(formFields.value.freeWordRules || []).splice(index, 1)
  }
}

function updateRule() {
  emit('on-update-rule')
}

function handleSubmit() {
  FormRef.value?.validate().then(() => {
    emit('on-submit')
  })
}

function handleCancel() {
  FormRef.value?.resetFields()
  visible.value = false
}
</script>

<style lang="scss" scoped>
.heat-rate {
  width: 266px;
}
</style>

<style lang="scss">
.activity-dialog {
  .ant-modal-content {
    max-height: 90vh;
    overflow: auto;
  }
}
</style>
